<template>
  <div class="maincontent">
    <el-form :inline="true" :model="form" label-width="90px" ref="formData" :rules="formDataRules">
      <div class="maintitle">测绘单位信息</div>
      <div class="formcontent">
        <div class="basicInformation">
          前期测绘单位：{{unitSection.company}}
          <span>测绘开始时间：{{unitSection.startTime}}</span>
          <span>测绘完成时间：{{unitSection.endTime}}</span>
        </div>
        <el-form-item
          label="项目负责人"
          label-width="90px"
          style="margin-right:60px;"
          prop="projectManagerId"
        >
          <el-select
            v-model="form.projectManagerId"
            placeholder="项目负责人"
            :disabled="isCurrentProcess"
          >
            <el-option
              v-for="item in enterpriseUsers"
              :key="item.userId"
              :label="item.name"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="前期测绘单位负责人"
          label-width="145px"
          style="margin-right:60px;"
          prop="companyManagerId"
        >
          <el-select
            v-model="form.companyManagerId"
            placeholder="测绘单位负责人"
            :disabled="isCurrentProcess"
          >
            <el-option
              v-for="item in enterpriseUsers"
              :key="item.userId"
              :label="item.name"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="前期测绘技术负责人" label-width="145px" prop="technicalManagerId">
          <el-select
            v-model="form.technicalManagerId"
            placeholder="前期测绘技术负责人"
            :disabled="isCurrentProcess"
          >
            <el-option
              v-for="item in enterpriseUsers"
              :key="item.userId"
              :label="item.name"
              :value="item.userId"
            ></el-option>
          </el-select>
        </el-form-item>
      </div>
      <div class="maintitle" style="margin-top:40px;">前期测绘基本信息</div>
      <div class="formcontent">
        <div class="basicInformationitem">图幅号：{{mappingBasicData.drawingNumber}}</div>
        <div style="clear:both;"></div>
        <div class="basicInformationitem">红线范围内总面积：{{mappingBasicData.totalAreaInRedline}}</div>
        <div class="basicInformationitem">可实施总规模：{{mappingBasicData.totalAreaForced}}</div>
        <div style="clear:both;"></div>
        <div class="basicInformationitem">可开发规模：{{mappingBasicData.totalAreaDevelop}}</div>
        <div class="basicInformationitem">可整理规模：{{mappingBasicData.totalAreaOrganized}}</div>
        <div class="basicInformationitem">可复垦规模：{{mappingBasicData.totalAreaReclaim}}</div>
        <div style="clear:both;"></div>
        <el-form-item
          label="地貌类型"
          label-width="78px"
          style="margin-right:60px;"
          prop="landFormType"
        >
          <el-input
            v-model="form.landFormType"
            placeholder="地貌类型"
            style="width:200px;"
            :disabled="isCurrentProcess"
          ></el-input>
        </el-form-item>
        <el-form-item label="土壤类型" label-width="78px" style="margin-right:60px;" prop="soilType">
          <el-input
            v-model="form.soilType"
            placeholder="土壤类型"
            style="width:200px;"
            :disabled="isCurrentProcess"
          ></el-input>
        </el-form-item>
        <el-form-item label="水源情况" label-width="78px" prop="waterSituation">
          <el-input
            v-model="form.waterSituation"
            placeholder="水源情况"
            style="width:200px;"
            :disabled="isCurrentProcess"
          ></el-input>
        </el-form-item>
      </div>
      <div class="maintitle" style="margin-top:40px;">耕地分坡度级面积（公顷）</div>
      <div class="formcontent">
        <el-table :data="slopeTypeList" style="width: 100%" class="slopeTable">
          <el-table-column prop="txt" label="类型" width="100px"></el-table-column>
          <el-table-column prop="dryLandArea" label="旱地面积">
            <template slot-scope="scope">
              <el-input v-model="scope.row.dryLandArea" :readonly="isCurrentProcess"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="dryLandFieldRatio" label="旱地田坎系数">
            <template slot-scope="scope">
              <el-input v-model="scope.row.dryLandFieldRatio" :readonly="isCurrentProcess"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="wetLandArea" label="水田面积">
            <template slot-scope="scope">
              <el-input v-model="scope.row.wetLandArea" :readonly="isCurrentProcess"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="wetLandFieldRatio" label="水田田坎系数">
            <template slot-scope="scope">
              <el-input v-model="scope.row.wetLandFieldRatio" :readonly="isCurrentProcess"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="otherGrassArea" label="其它草地面积">
            <template slot-scope="scope">
              <el-input v-model="scope.row.otherGrassArea" :readonly="isCurrentProcess"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="maintitle" style="margin-top:40px;">前期测绘成果</div>
      <div class="formcontent">
        <el-form-item label="前期测绘成果模板" label-width="128px" v-if="!isCurrentProcess">
          <el-button size="small" type="primary" @click="handleDownload">点击下载</el-button>
        </el-form-item>
      </div>
      <div>
        <el-form-item label="前期测绘成果" label-width="128px" prop="resultFileId">
          <el-upload
            ref="uploadMappingZip"
            :http-request="uploadMappingZip"
            class="upload-demo"
            action="upload"
            :file-list="fileList"
            :on-success="uploadMappingZipSuccess"
            accept=".zip"
            :disabled="isCurrentProcess"
            v-if="!isCurrentProcess"
          >
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
          <div class="viewDocment" v-if="isCurrentProcess">
            <seeFujian
              v-if="form.resultFile"
              @openPdf="seePdf"
              download="1"
              :file-name="form.resultFile | backFileName"
              :file-url="form.resultFile | backFilePath(baseUrl)"
            />

            <!-- <span><i class="el-icon-document"/>{{form.resultFile | backFileName}}</span>
            <a :href="form.resultFile | backFilePath(baseUrl)" target="_blank" style="color: rgb(64, 158, 255);margin-left:5px">下载</a>-->
          </div>
        </el-form-item>
      </div>
      <div>
        <el-form-item>
          <el-button
            type="primary"
            @click="onSubmit"
            :disabled="noSubmitFlag"
            v-if="!isCurrentProcess"
          >提交</el-button>
          <el-button @click="$router.push('/projectManagement/planningStage/dealwith')">返回</el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
import {
  getUnitInputData,
  getUnitSectionData,
  getMappingBasicData,
  userByEnterprise,
  saveMappingResult,
  uploadEarlyMappingZip
} from "@/api/earlyMapping/unitInput";
import config from "@/config/index";
import seeFujian from "@/components/seeFujian";
export default {
  components: {
    seeFujian
  },
  data() {
    return {
      noSubmitFlag: false,
      projectId: localStorage.getItem("projectId") * 1,
      mappingResultTemplateDownload: `${config.baseUrl}/renovation/templatefile/前期测绘上传数据.zip`,
      uploadUrl: config.uploadUrl, //上传接口
      baseUrl: config.baseUrl,
      historyData: {}, // 历史数据
      fileList: [],
      unitSection: { company: "", startTime: "", endTime: "" }, // 测量单位信息
      mappingBasicData: {
        drawingNumber: "",
        totalAreaInRedline: "",
        totalAreaForced: "",
        totalAreaDevelop: "",
        totalAreaOrganized: "",
        totalAreaReclaim: ""
      }, // 前期测绘基础信息,
      enterpriseUsers: [], // 企业人员列表
      slopeTypeList: [
        {
          slopeType: 1,
          txt: "0°-2°",
          dryLandArea: "",
          dryLandFieldRatio: "",
          wetLandArea: "",
          wetLandFieldRatio: "",
          otherGrassArea: ""
        },
        {
          slopeType: 2,
          txt: "2°-6°",
          dryLandArea: "",
          dryLandFieldRatio: "",
          wetLandArea: "",
          wetLandFieldRatio: "",
          otherGrassArea: ""
        },
        {
          slopeType: 3,
          txt: "6°-15°",
          dryLandArea: "",
          dryLandFieldRatio: "",
          wetLandArea: "",
          wetLandFieldRatio: "",
          otherGrassArea: ""
        },
        {
          slopeType: 4,
          txt: "15°-25°",
          dryLandArea: "",
          dryLandFieldRatio: "",
          wetLandArea: "",
          wetLandFieldRatio: "",
          otherGrassArea: ""
        }
      ],
      form: {
        projectId: "",
        companyManagerId: "",
        projectManagerId: "",
        technicalManagerId: "",
        landFormType: "",
        soilType: "",
        waterSituation: "",
        resultFileId: "",
        landAreaBySlopeList: ""
      },
      formDataRules: {
        companyManagerId: [
          {
            require: true,
            validator(rule, value, callback) {
              const v = Number(value);
              if (isNaN(v) || !v) {
                callback(new Error("请选择测绘单位负责人"));
              }
              callback();
            },
            trigger: "change",
            type: "number"
          }
        ],
        projectManagerId: [
          {
            require: true,
            validator(rule, value, callback) {
              const v = Number(value);
              if (isNaN(v) || !v) {
                callback(new Error("请选择项目负责人"));
              }
              callback();
            },
            trigger: "change",
            type: "number"
          }
        ],
        technicalManagerId: [
          {
            require: true,
            validator(rule, value, callback) {
              const v = Number(value);
              if (isNaN(v) || !v) {
                callback(new Error("请选择技术负责人"));
              }
              callback();
            },
            trigger: "change",
            type: "number"
          }
        ],
        soilType: [
          {
            require: true,
            validator(rule, value, callback) {
              if (value === "") {
                callback(new Error("不能为空"));
              }
              callback();
            },
            trigger: "blur"
          }
        ],
        landFormType: [
          {
            require: true,
            validator(rule, value, callback) {
              if (value === "") {
                callback(new Error("不能为空"));
              }
              callback();
            },
            trigger: "blur"
          }
        ],
        waterSituation: [
          {
            require: true,
            validator(rule, value, callback) {
              if (value === "") {
                callback(new Error("不能为空"));
              }
              callback();
            },
            trigger: "blur"
          }
        ],
        resultFileId: [
          {
            require: true,
            validator: (rule, value, callback) => {
              const v = Number(value);
              if (isNaN(v) || !v) {
                this.$message.error("请上传前期测绘成果后再提交");
                callback(new Error(""));
              }
              callback();
            },
            trigger: "blur"
          }
        ]
      }
    };
  },
  computed: {
    isCurrentProcess: function() {
      let isTrue = localStorage.getItem("key") == "PRE_PROJECTING_MEDIUM_ENTRT";
      if (localStorage.getItem("lookStatus") == 2) {
        isTrue = false;
      }
      return !isTrue;
    }
  },
  filters: {
    backFileName: function(data) {
      if (data) {
        return data.fileName;
      } else {
        return "";
      }
    },
    backFilePath: function(data, baseUrl) {
      if (data) {
        return baseUrl + data.filePath;
      } else {
        return "#";
      }
    }
  },
  created() {
    this._initData();
  },
  methods: {
    onSubmit() {
      this.form.projectId = this.projectId;
      this.form.landAreaBySlopeList = this.slopeTypeList;
      this.form.drawingNumber = this.mappingBasicData.drawingNumber;
      this.form.totalAreaInRedline = this.mappingBasicData.totalAreaInRedline;
      this.form.totalAreaForced = this.mappingBasicData.totalAreaForced;
      this.form.totalAreaDevelop = this.mappingBasicData.totalAreaDevelop;
      this.form.totalAreaOrganized = this.mappingBasicData.totalAreaOrganized;
      this.form.totalAreaReclaim = this.mappingBasicData.totalAreaReclaim;
      let isTrue = false;
      this.$refs["formData"].validate(valid => {
        isTrue = Boolean(valid);
      });
      if (isTrue) {
        const loading = this.$loading({
          lock: true,
          text: "Loading",
          spinner: "el-icon-loading",
          background: "rgba(0, 0, 0, 0.7)"
        });
        saveMappingResult(this.form)
          .then(res => {
            this.$message.success("操作成功！");
            loading.close();
            this.$router.push("/projectManagement/planningStage/dealwith");
          })
          .catch(err => {
            loading.close();
          });
      }
    },
    // 历史数据
    getHistoryData() {
      const loading = this.$loading({
        lock: true,
        text: "Loading",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)"
      });
      getUnitInputData(this.projectId)
        .then(res => {
          if (res.data) {
            this.form = res.data;
            const stl = this.slopeTypeList.slice();
            this.slopeTypeList = stl.map((it, index) => {
              return Object.assign(it, res.data.landAreaBySlopeList[index]);
            });
            if (res.data.resultFile) {
              this.fileList = [
                {
                  name: res.data.resultFile.fileName,
                  url: res.data.resultFile.filePath
                }
              ];
            }
            console.log(this.form);
          }
          loading.close();
        })
        .catch(err => {
          loading.close();
        });
    },
    // 测量单位信息
    getUnitSection() {
      getUnitSectionData(this.projectId).then(res => {
        if (res.data) {
          this.unitSection = res.data;
          this.getUserByEnterpriseList();
        }
      });
    },
    // 前期测绘基本信息
    getMappingBasic() {
      getMappingBasicData(this.projectId).then(res => {
        if (res.data) {
          this.mappingBasicData = res.data;
        }
      });
    },
    // 获取企业人员
    getUserByEnterpriseList() {
      //console.log(this.unitSection)
      userByEnterprise(this.unitSection.companyId).then(res => {
        if (res.data) {
          this.enterpriseUsers = res.data;
        }
      });
    },
    // 上传前期测绘成果文件ZIP
    uploadMappingZip(content) {
      let fd = new window.FormData();
      fd.append("file", content.file);
      fd.append("projectId", localStorage.getItem("projectId"));
      this.noSubmitFlag = true;
      uploadEarlyMappingZip(fd)
        .then(res => {
          content.onSuccess(res, content.file, [content.file]);
        })
        .catch(error => {
          if (error.response) {
            content.onError(
              "文件上传失败(" +
                error.response.status +
                ")，" +
                error.response.data
            );
          } else {
            content.onError("上传文件失败,请重试");
          }
        });
    },
    // 上传前期测绘压缩包成功
    uploadMappingZipSuccess(res, file, fileList) {
      this.noSubmitFlag = false;
      if (res.data.successData) {
        this.mappingBasicData = res.data.successData;
        this.form["resultFileId"] = this.mappingBasicData.resultFileId;
      } else {
        this.$refs["uploadMappingZip"].clearFiles();
        let errorFiles = res.data.failData
          .map((item, index) => {
            return index + 1 + "." + item.fileName;
          })
          .join("。");
        this.$confirm(
          `存在以下文件错误（${errorFiles}）,请重新修改后上传`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "error"
          }
        );
      }
    },
    // 下载前期测绘成果模板
    handleDownload() {
      let a = document.createElement("a");
      a.href = this.mappingResultTemplateDownload;
      a.click();
    },
    _initData() {
      this.getHistoryData();
      this.getUnitSection();
      this.getMappingBasic();
    }
  }
};
</script>

<style lang="scss" scoped>
.maincontent {
  padding: 30px 40px;
  .maintitle {
    font-size: 18px;
    font-family: PingFang SC;
    font-weight: bold;
    line-height: 25px;
    color: #4d4d4d;
  }
  .formcontent {
    margin-top: 30px;
    .basicInformation {
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 500;
      line-height: 20px;
      color: #8c8c8c;
      margin-bottom: 20px;
      span {
        margin-left: 60px;
      }
    }
    .basicInformationitem {
      font-size: 14px;
      font-family: PingFang SC;
      font-weight: 500;
      line-height: 20px;
      color: #8c8c8c;
      float: left;
      width: 251px;
      margin-bottom: 20px;
    }
  }
}
</style>
<style lang="scss" scoped>
.formcontent {
  .slopeTable {
    /deep/ .el-input__inner {
      // border: 0;
      transition: background-color 0.25s ease;
    }
    /deep/ .el-table__body tr:hover /deep/ .el-input__inner {
      background: #f5f7fa;
    }
  }
}
</style>
